<?php
    function getTemplate( $templateName )
    {
        $file = file( $templateName );
        if ( $file )
        {
            return implode( $file );
        }
    }
    function parseTemplate( $templateName, $vars )
    {
        if ( empty( $templateName ) || !file_exists( $templateName ) )
        {
            return false;
        }
        else
        {
            $file = file( $templateName );
            if ( $file )
            {
                for ( $i = 0; $i < sizeof( $file ); $i++ )
                {
                    foreach( $vars as $key => $value )
                    {
                        $file[$i] = str_replace( '{%'.$key.'%}', $value, $file[$i] );
                    }
                }
                return implode( $file );
            }
        }
    }
    function buildLayout( $vars )
    {
        session_start();
        $content = $vars['CONTENT'];
        $head = parseTemplate( 'head.tpl', $vars );
        if ( isset($_SESSION['user_name'] ) )
        {
            $vars = array( 'USER_NAME' => $_SESSION['user_name'] );
            $formEnter = parseTemplate( 'form_exit.tpl', $vars );
        }
        else
        {
            $formEnter = getTemplate( 'form_enter.tpl' );
        }
        $vars = array( 'FORM_ENTER' => $formEnter );
        $header = parseTemplate( 'header.tpl', $vars );
        $menuNavigation = getTemplate( 'menu_navigation.tpl' );
        $vars = array( 'MENU_NAVIGATION' => $menuNavigation );
        $sidebar = parseTemplate( 'sidebar.tpl', $vars );
        $footer = getTemplate( 'footer.tpl' );
        $vars = array( 'HEAD' => $head, 'HEADER' => $header, 'SIDEBAR' => $sidebar, 'CONTENT' => $content, 'FOOTER' => $footer );
        echo parseTemplate( 'index.tpl', $vars );
    }
?>